package net.garbage;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author Jose Martin Rozanec;
 */
public class ClientPort extends NetPortToClient {
    public ClientPort(RemoteFileInputServer server, Socket socket) throws IOException {
        super(server, socket);
        start(); // as a thread
    }

    public void processInput() throws IOException {
        byte value = readByte();
        //todo ver este bloque de procesamiento
        if (value == 0) {
            this.write("server".getBytes());
        } else {
            System.out.print("" + (char) value);
        }
        //todo END OF ver este bloque de procesamiento
    }

    public void readInput() throws IOException {

        try {
            String filename = readUTF();
            process(filename.trim());
        }
        catch (IOException ioe) {
            System.err.println(
                    "Error reading filename from the client.\nClient probably disconnected");
            stop();
        }
    }

    private synchronized void process(String filename) {
        try {
            InputStream file = new BufferedInputStream(new FileInputStream(filename));
            writeInt(file.available());
            int byteread;
            while ((byteread = file.read()) >= 0) {
                writeByte(byteread);
            }
            flush();
        }
        catch (IOException ioe) {
            System.err.println("Error reading file \"" + filename + "\" for the client.");
//                writeInt(-1);
//                flush();
        }
    }
}